package com.yonyou.pmclouds.workflow.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.yonyou.pmclouds.basecom.entity.SuperVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.workflow.entity.ProcessTaskVO;
import com.yonyou.pmclouds.workflow.util.WorkFlowConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import yonyou.bpm.rest.TaskService;
import yonyou.bpm.rest.exception.RestException;
import yonyou.bpm.rest.request.AssignInfo;
import yonyou.bpm.rest.request.TaskActionTypeEnum;
import yonyou.bpm.rest.request.task.TaskActionParam;
import yonyou.bpm.rest.request.task.TaskQueryParam;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ProcessTaskService {

    private TaskService taskService;

    public TaskService getDefaultTaskService() throws BusinessException {
        taskService = (TaskService) ProcessServiceFactory.getProcessService(ProcessServiceFactory.TASK_SERVICE,
                RuntimeEnvironment.getLoginUserId(),RuntimeEnvironment.getTenantId());
        return taskService;
    }

    /**
     * 查询流程待办信息
     */
    public ProcessTaskVO[] queryProcessTaskVOs(TaskQueryParam param) throws BusinessException{
        JsonNode jsonNode;
        try {
            Object resultObj = getDefaultTaskService().queryTasks(param);
            if(resultObj == null)
                throw new BusinessException(WorkFlowConst.YS_NULL_RESP_MSG);
            jsonNode = (JsonNode) resultObj;
        } catch (RestException e) {
            log.error(e.getMessage(),e);
            throw new BusinessException("查询流程待办信息失败：" + e.getMessage());
        }


        JsonNode data = jsonNode.get("data");

        List<ProcessTaskVO> processTaskVOList = new ArrayList<ProcessTaskVO>();
        for (JsonNode taskInfo :
                data) {
            ProcessTaskVO processTaskVO = new ProcessTaskVO();
            processTaskVO.setPkReceiver(taskInfo.get("assignee").textValue());
            processTaskVO.setTaskId(taskInfo.get("id").textValue());
            processTaskVO.setProcessInstanceId(taskInfo.get("processInstanceId").textValue());

            processTaskVOList.add(processTaskVO);
        }
        if(processTaskVOList.size() == 0)
            return new ProcessTaskVO[0];
        return processTaskVOList.toArray(new ProcessTaskVO[0]);
    }

    /**
     * 完成任务
     * @param taskId 任务ID
     */
    public String completeTask(String taskId,String opinion, SuperVO buziVO, AssignInfo assignInfo) throws BusinessException {
        long startTime = System.currentTimeMillis();
        JsonNode resultNode;
        try {
            TaskActionParam taskActionParam = new TaskActionParam();
            taskActionParam.setMessageType("comment");
            taskActionParam.setMessage(opinion);
            taskActionParam.setTaskVariables(ProcessVariableProcessor.getVariableList(buziVO));
            if(assignInfo!=null){
                taskActionParam.setAssignInfo(assignInfo);
            }
            taskActionParam.setAction(TaskActionTypeEnum.complete);
            Object resultObj = taskService.actionTask(taskId, taskActionParam);
            if(resultObj == null)
                throw new BusinessException(WorkFlowConst.YS_NULL_RESP_MSG);
            resultNode = (JsonNode)resultObj;
        }catch (RestException e){
            log.error(e.getMessage(),e);
            throw new BusinessException("审批通过失败 : " + e.getMessage());
        }
        log.debug("审批完成方法耗时：" + (System.currentTimeMillis() - startTime));
        return resultNode.toString();
    }
}
